import { mapGetters } from 'vuex';
import { getList, getDetail, add, update, remove, getLazyList, lazyLoadChild } from '@/api/admin/partcategory';

export const MixMinxins = {
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.partcategory_add, false),
        viewBtn: this.vaildData(this.permission.partcategory_view, false),
        delBtn: this.vaildData(this.permission.partcategory_delete, false),
        editBtn: this.vaildData(this.permission.partcategory_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  methods: {
    handleAdd(row) {
      this.parentId = row.id;
      const column = this.findObject(this.option.column, 'parentId');
      column.value = row.id;
      column.addDisabled = true;
      this.$refs.crud.rowAdd();
    },
    rowSave(row, done, loading) {
      this.$refs.crud.validate((valid, validDone) => {
        if (valid) {
          let flag = this.checkOverlimitRate();
          if (flag) {
            this.$message({
              type: 'warning',
              message: '请输入超收比例！'
            });
            validDone();
            return;
          }
          if (Number(this.form.overlimitRate) < 0) {
            this.$message({
              type: 'warning',
              message: '超收比例不能小于0！'
            });
            validDone();
            return;
          }
          let isValid = this.checkOverCollarMentRatio();
          if (isValid) {
            this.$message({
              type: 'warning',
              message: '请输入超领比例!'
            });
            validDone();
            return;
          }
          if (Number(this.form.overCollarRate) < 0) {
            this.$message({
              type: 'warning',
              message: '超领比例不能小于0！'
            });
            validDone();
            return;
          }
          add(row).then(
            (res) => {
              if (this.parentId === '') {
                this.treeParams = new Map();
              }
              if (JSON.stringify(this.treeParams) === '[]') {
                // 刷新表格数据并重载
                this.data = [];
                this.parentId = 0;
                this.$refs.crud.refreshTable();
                this.$refs.crud.toggleSelection();
                this.onLoad(this.page);
              } else {
                // 获取新增数据的相关字段
                this.treeParams.forEach((item, key) => {
                  const { tree, treeNode, resolve } = this.treeParams.get(key);
                  this.treeLoad(tree, treeNode, resolve);
                });
              }
              // this.data = [];
              // this.parentId = 0;
              // // 表格数据重载
              // this.onLoad(this.page);
              this.$message({
                type: 'success',
                message: '操作成功!'
              });
              done();
            },
            (error) => {
              loading();
            }
          );
        }
      });
    },
    rowUpdate(row, index, done, loading) {
      this.$refs.crud.validate((valid, validDone) => {
        if (valid) {
          let flag = this.checkOverlimitRate();
          if (flag) {
            this.$message({
              type: 'warning',
              message: '请输入超收比例！'
            });
            validDone();
            return;
          }
          if (Number(this.form.overlimitRate) < 0) {
            this.$message({
              type: 'warning',
              message: '超收比例不能小于0！'
            });
            validDone();
            return;
          }
          let isValid = this.checkOverCollarMentRatio();
          if (isValid) {
            this.$message({
              type: 'warning',
              message: '请输入超领比例!'
            });
            validDone();
            return;
          }
          if (Number(this.form.overCollarRate) < 0) {
            this.$message({
              type: 'warning',
              message: '超领比例不能小于0！'
            });
            validDone();
            return;
          }
          update(row).then(
            () => {
              if (JSON.stringify(this.treeParams) === '[]') {
                // 刷新表格数据并重载
                this.data = [];
                this.parentId = 0;
                this.$refs.crud.refreshTable();
                this.$refs.crud.toggleSelection();
                this.onLoad(this.page);
              } else {
                // 获取新增数据的相关字段
                this.treeParams.forEach((item, key) => {
                  const { tree, treeNode, resolve } = this.treeParams.get(key);
                  this.treeLoad(tree, treeNode, resolve);
                });
              }
              this.$message({
                type: 'success',
                message: '操作成功!'
              });
              done();
            },
            (error) => {
              loading();
              console.log(error);
            }
          );
        }
      });
    },
    rowDel(row, index, done) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done(row);
        });
    },
    handleDelete(row) {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          // 刷新表格数据并重载
          this.data = [];
          this.parentId = 0;
          this.$refs.crud.refreshTable();
          this.$refs.crud.toggleSelection();
          // 表格数据重载
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },

    beforeClose(done) {
      this.parentId = '';
      const column = this.findObject(this.option.column, 'parentId');
      column.value = 0;
      column.addDisabled = false;
      done();
    },
    searchReset() {
      this.query = {};
      this.parentId = 0;
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.parentId = 0;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getLazyList(this.parentId, page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data =
          res.data.data &&
          res.data.data.records &&
          res.data.data.records.map((item, index) => {
            item.dataIndex = index + 1;
            return item;
          });
        this.page.total = res.data.data.total;
        this.data = data;
        this.loading = false;
        this.selectionClear();
        this.treeParams = new Map();
      });
    },

    treeLoad(tree, treeNode, resolve) {
      const parentId = tree.id;
      this.treeParams.set(parentId, { tree, treeNode, resolve });
      lazyLoadChild(parentId).then((res) => {
        let data = res.data.data;
        resolve(data);
      });
    }
  }
};
